<template>
    <div class="avatar-container">
    <!-- 竖屏虚拟人显示区域 -->
    <div class="avatar-display">
      <div class="avatar-wrapper" id="wrapper"></div>
    </div>

    <!-- 底部按钮控制区域 -->
    <!-- <div class="control-panel">
      <div class="control-buttons">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-button @click="startAll()" type="primary" class="control-button">
              开始初始化
            </el-button>
          </el-col>
          <el-col :span="8">
            <el-button @click="startVirtualHuman()" type="primary" class="control-button">
              启动虚拟人
            </el-button>
          </el-col>
          <el-col :span="8">
          </el-col>
          <el-col :span="8">
            <el-button @click="closeAll()" type="primary" class="control-button">
              关闭释放
            </el-button>
          </el-col>
        </el-row>
      </div>
    </div> -->

      <!--SetApiInfo悬浮框（保留参数配置功能）-->
      <el-dialog title="初始化SDK" :visible.sync="SetApiInfodialog">
        <el-form :model="form">
          <span>此处参数均去交互平台-接口服务中获取</span>
          <el-form-item label="Appid" :label-width="formLabelWidth">
            <el-input class="widthclass" v-model="form.appid" autocomplete="off"></el-input>
            <span>必填</span>
          </el-form-item>
          <!-- 其他表单字段保持不变 -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="SetApiInfodialog = false">取消</el-button>
          <el-button type="primary" @click="(SetApiInfodialog = false), SetApiInfo2()">确定</el-button>
        </div>
      </el-dialog>

      <!--SetGlobalParams悬浮框（保留参数配置功能）-->
      <el-dialog title="设置全局变量" :visible.sync="SetGlobalParamsdialog">
        <div style="text-align: center"><h3>打断模式全局设置</h3></div>
        <el-form :model="setglobalparamsform" :label-width="formLabelWidth">
          <!-- 表单字段保持不变 -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="SetGlobalParamsdialog = false">取消</el-button>
          <el-button type="primary" @click="(SetGlobalParamsdialog = false), SetGlobalParams()">确定</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import AvatarPlatform, {
  PlayerEvents,
  SDKEvents,
} from "../vm-sdk/avatar-sdk-web_3.1.1.1011/index.js";

// 初始化透明度控制
document.addEventListener("DOMContentLoaded", function() {
  const div = document.getElementById('wrapper');
  const range = document.getElementById('opacityRange');
  range.addEventListener('input', function() {
    div.style.opacity = this.value;
  });
});

let avatarPlatform2 = null;
let recorder = null;
let actionTimer = null; // 动作定时器
export default {
  name: "avatarComponent",
  data() {
    return {
      SetApiInfodialog: false,
      SetGlobalParamsdialog: false,
      form: {
        appid: "9e4cccaa",
        apikey: "2d359ab727b0dc601f911bbd9bcb2d09",
        apisecret: "NDg5YWYyMWY0YWRiMzA2Yzg4NGNiZmRk",
        sceneid: "199103744200282112",
        serverurl: "wss://avatar.cn-huadong-1.xf-yun.com/v1/interact",
      },
      setglobalparamsform: {
        stream: {
          protocol: "xrtc",
          fps: 25,
          bitrate: 1000000,
          alpha: true,
        },
        avatar: {
          avatar_id: "110332017",
          width: 1080,
          height: 1920,
        },
        tts: {
          vcn: "x4_panting",
        },
        avatar_dispatch: {
          interactive_mode: 1,
        },
        subtitle: {
          subtitle: 2,
          font_color: "#683003",
        },
        enable: false,
        background: {
          type: "res_key",
          data: "22SLM2teIw+aqR6Xsm2JbH6Ng310kDam2NiCY/RQ9n6s3nYJXloZWW1l64/g32vrn7d2lJQR7m9xD5EHYkVs15TqlX3gcacJiRdGoSYNZJ7aH7WspvOIt4XMuVbH1PN2EKxqmFfIYQ3lMqcblfNug0dOD6lU837XOuSqc95h8Z/kTq0F2dq1b5/Z+89Lg9t3kgqNxEol5EkBGHVTnoRHyhjmCPRwTtCIaVhECKpntVc9PPutjKLZL3mL+oTr0OZEsTXWpOEOJBhOBX6A9VPx2IUmxnQilc3o0Ytmu2P3g5G2WCh9R2/mA7vpO1ZgQObhA4IcA4j8qwrfaJpVG8J4iIFtZObkZFvvxvAqo+3I9jk=",
        }
      },
      formLabelWidth: "120px",
      textarea: "欢迎咨询，我是您的AI面试小助手，请查看您选择的面试岗位的具体要求，如果有什么其他问题，也可以咨询我哦～",
      vc: "",
      recorderbutton: false,
      nlp: false,
      emotion: 0,
      action: "",
      volume: 100,
      actionTimerRunning: false // 定时器运行状态
    };
  },
  methods: {
    // 整合六大初始化功能
    startAll() {
      this.initSDK();
      this.setSDKEvenet();
      this.setPlayerEvenet();
      this.SetApiInfo2();
      this.SetGlobalParams();
    },

    // 整合启动和录音功能
    startVirtualHuman() {
      this.start();
      this.sendTextToAvatar();
    },

    // 整合关闭和销毁功能
    closeAll() {
      this.stop();
      this.destroy();
      this.stopActionTimer(); // 停止动作定时器
    },

    // 基础功能 - 实例化SDK
    initSDK() {
      avatarPlatform2 = new AvatarPlatform();
      if (avatarPlatform2) {
        //this.open2("实例化SDK成功");
      }
    },

    // 基础功能 - 设置SDK监听
    setSDKEvenet() {
      if (avatarPlatform2) {
        avatarPlatform2
          .on(SDKEvents.connected, (initResp) => console.log("SDK连接成功", initResp))
          .on(SDKEvents.error, (error) => console.error("SDK错误", error));
        //this.open2("SDK监听设置成功");
      } else {
        alert("请先实例化SDK");
      }
    },

    // 基础功能 - 设置播放器监听
    setPlayerEvenet() {
      if (avatarPlatform2) {
        const player = avatarPlatform2.createPlayer();
        player.on(PlayerEvents.play, () => console.log("播放开始"));
        //this.open2("播放器监听设置成功");
      } else {
        alert("请先实例化SDK");
      }
    },
    // 新增文本驱动方法
    sendTextToAvatar() {
      if (!avatarPlatform2) {
        //this.$message.error("请先初始化SDK");
        return;
      }

      const text = this.textarea.trim();
      if (!text) {
        //this.$message.error("文本内容不能为空");
        return;
      }

      // 构建文本发送参数
      const textParams = {
        nlp: this.nlp, // 是否开启语义理解
        tts: {
          vcn: this.vc || this.setglobalparamsform.tts.vcn, // 使用变声ID或默认声音ID
          volume: this.volume,
          emotion: this.emotion
        }
      };

      // 发送文本到虚拟人
      avatarPlatform2.writeText(text, textParams)
        .then(() => {
          //this.$message.success("文本已发送，虚拟人即将开始朗读");
          console.log("文本发送成功:", text);
        })
        .catch(error => {
          //this.$message.error("文本发送失败: " + error.message);
          console.error("文本发送错误:", error);
        });
    },

    // 基础功能 - 设置API信息
    SetApiInfo2() {
      if (avatarPlatform2) {
        const params = {
          appId: this.form.appid,
          apiKey: this.form.apikey,
          apiSecret: this.form.apisecret,
          serverUrl: this.form.serverurl,
          sceneId: this.form.sceneid,
        };
        avatarPlatform2.setApiInfo(params);
        //this.open2("API信息设置成功");
      } else {
        alert("请先实例化SDK");
      }
    },

    // 基础功能 - 设置全局参数
    SetGlobalParams() {
      if (avatarPlatform2) {
        let params = { ...this.setglobalparamsform };
        params.stream.alpha = params.stream.alpha ? 1 : 0;
        if (!params.enable) {
          delete params.background;
          delete params.enable;
        }
        avatarPlatform2.setGlobalParams(params);
        //this.open2("全局参数设置成功");
      } else {
        alert("请先实例化SDK");
      }
    },

    // 基础功能 - 启动虚拟人
    start() {
      if (avatarPlatform2) {
        avatarPlatform2.start({ wrapper: document.querySelector("#wrapper") })
          .catch((e) => console.error("启动错误", e));
      } else {
        alert("请先实例化SDK");
      }
    },

    // 基础功能 - 关闭连接
    stop() {
      if (avatarPlatform2) {
        avatarPlatform2.stop();
      } else {
        alert("请先实例化SDK");
      }
    },

    // 基础功能 - 销毁SDK
    destroy() {
      if (avatarPlatform2) {
        avatarPlatform2.destroy();
        avatarPlatform2 = null;
      } else {
        alert("请先实例化SDK");
      }
    },

    // 提示消息
    open2(text) {
      this.$message({
        message: text,
        type: "success",
        duration: 2000
      });
    }
  },
  writeText() {
      if(avatarPlatform2 != null){
      const text = this.textarea;
      if (text != "" && this.vc == "") {
        avatarPlatform2.writeText(text, {
          nlp: this.nlp,//是否开启语义理解
          tts: {
            volume: 100,
          },
        });
      } else if (text != "" && this.vc != ""){
        avatarPlatform2.writeText(text, {
          nlp: this.nlp,//是否开启语义理解
          tts: {
            vcn:this.vc,//变声
            volume: 100,
            emotion:this.emotion,
          },
        });
      }else {
        alert("内容不许为空");
      }
      }else {
        alert("请先实例化SDK")
      }

    },
  beforeDestroy() {
    if (avatarPlatform2) {
      avatarPlatform2.stop();
    }
    this.stopActionTimer(); // 组件销毁时停止定时器
  }
};
</script>

<style scoped>
/* 整体容器 */
.avatar-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background-color: #f5f7fa;
}

/* 虚拟人显示区域 - 竖屏布局 */
.avatar-display {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background-color: #00000000; /* 黑色背景更适合虚拟人显示 */
}

.avatar-wrapper {
  height: 100%; /* 占据视口高度的80% */
  width: auto;
  aspect-ratio: 9/16; /* 保持9:16的竖屏比例 */
  max-width: 100%;
  max-height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
/* 文本输入区域 */
.text-input-area {
  flex: 1;
  padding: 15px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

/* 底部控制区域 */
.control-panel {
  background-color: #fff;
  padding: 15px;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.control-buttons {
  max-width: 1200px;
  margin: 0 auto;
}

/* 按钮样式 */
.control-button {
  width: 100%;
  margin: 5px 0;
  height: 40px;
}

.control-input {
  margin: 5px 0;
}

.control-item {
  margin: 10px 0;
  display: flex;
  align-items: center;
  padding: 0 10px;
}

.control-item span {
  margin-right: 10px;
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.control-item input[type="range"] {
  flex: 1;
}

.widthclass {
  width: 350px;
}

span {
  color: red;
  font-size: 12px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-col {
    width: 100%;
    margin-bottom: 10px;
  }

  .avatar-wrapper {
    height: 70vh;
  }
}
</style>
